// service/UserService.java
package main.java.com.cinema.service;

import main.java.com.cinema.model.User;
import main.java.com.cinema.dao.UserDAO;
import main.java.com.cinema.util.Logger;

import java.util.List;
import java.util.UUID;

public class UserService {
    private UserDAO userDAO = new UserDAO();

    public User login(String username, String password) {
        User user = userDAO.findByUsername(username);
        if (user != null && user.verifyPassword(password)) {
            return user;
        }
        return null;
    }

    public boolean changePassword(String userId, String oldPassword, String newPassword) {
        User user = userDAO.findById(userId);
        if (user != null && user.verifyPassword(oldPassword)) {
            user.setPassword(newPassword);
            user.setPasswordChanged(true);
            userDAO.update(user);

            // 记录日志
            Logger.log("修改密码", "用户 " + user.getUsername() + " 修改了密码", "系统");
            return true;
        }
        return false;
    }

    public boolean resetPassword(String adminId, String targetUserId) {
        User admin = userDAO.findById(adminId);
        User targetUser = userDAO.findById(targetUserId);

        if (admin != null && targetUser != null &&
                (admin.getRole() == User.Role.ADMIN ||
                        (admin.getRole() == User.Role.MANAGER && targetUser.getRole() == User.Role.STAFF))) {

            targetUser.setPassword("123456");
            targetUser.setPasswordChanged(false); // 重置后需要重新修改
            userDAO.update(targetUser);

            // 记录日志
            String operationType = "重置" + getRoleName(targetUser.getRole()) +
                    " " + targetUser.getUsername() + " 的密码";
            Logger.log("重置密码", operationType, admin.getUsername());
            return true;
        }
        return false;
    }

    public List<User> listAllUsers() {
        return userDAO.findAll();
    }

    public User findUserById(String userId) {
        return userDAO.findById(userId);
    }

    public User findUserByUsername(String username) {
        return userDAO.findByUsername(username);
    }

    public boolean addUser(User adminUser, String username, String password,
                           User.Role role, String phoneNumber) {
        // 检查权限
        if (adminUser.getRole() != User.Role.ADMIN) {
            return false;
        }

        // 检查唯一性
        if (userDAO.findByUsername(username) != null) {
            return false; // 用户名已存在
        }

        // 检查手机号唯一性
        List<User> allUsers = userDAO.findAll();
        for (User user : allUsers) {
            if (user.getPhoneNumber() != null && user.getPhoneNumber().equals(phoneNumber)) {
                return false; // 手机号已存在
            }
        }

        // 创建新用户
        String userId = "U" + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
        User newUser = new User(userId, username, password, role, phoneNumber);

        boolean result = userDAO.save(newUser);
        if (result) {
            // 记录日志
            String operationType = "增加" + getRoleName(role) + " " + username;
            Logger.log("增加用户", operationType, adminUser.getUsername());
        }
        return result;
    }

    public boolean updateUser(User adminUser, String userId, User.Role newRole, String newPhoneNumber) {
        // 检查权限
        if (adminUser.getRole() != User.Role.ADMIN) {
            return false;
        }

        User user = userDAO.findById(userId);
        if (user == null || "admin".equals(user.getUsername())) {
            return false; // 不能修改admin账户
        }

        // 检查手机号唯一性（排除当前用户）
        List<User> allUsers = userDAO.findAll();
        for (User u : allUsers) {
            if (!u.getUserId().equals(userId) &&
                    u.getPhoneNumber() != null &&
                    u.getPhoneNumber().equals(newPhoneNumber)) {
                return false; // 手机号已存在
            }
        }

        user.setRole(newRole);
        user.setPhoneNumber(newPhoneNumber);
        userDAO.update(user);

        // 记录日志
        String operationType = "修改" + getRoleName(user.getRole()) +
                " " + user.getUsername() + " 的信息";
        Logger.log("修改用户", operationType, adminUser.getUsername());
        return true;
    }

    public boolean deleteUser(User adminUser, String userId) {
        // 检查权限
        if (adminUser.getRole() != User.Role.ADMIN) {
            return false;
        }

        User user = userDAO.findById(userId);
        if (user == null || "admin".equals(user.getUsername())) {
            return false; // 不能删除admin账户
        }

        boolean result = userDAO.delete(userId);
        if (result) {
            // 记录日志
            String operationType = "删除" + getRoleName(user.getRole()) +
                    " " + user.getUsername();
            Logger.log("删除用户", operationType, adminUser.getUsername());
        }
        return result;
    }

    private String getRoleName(User.Role role) {
        switch (role) {
            case ADMIN: return "管理员";
            case MANAGER: return "经理";
            case STAFF: return "前台";
            default: return "用户";
        }
    }
}
